import { useState, useCallback } from 'react';
import { message } from 'antd';

export interface PaginationState {
  current: number;
  pageSize: number;
  total: number;
}

export interface PaginationConfig {
  initialPage?: number;
  initialPageSize?: number;
  showSizeChanger?: boolean;
  showQuickJumper?: boolean;
  showTotal?: boolean | ((total: number) => string);
}

export interface UsePaginationResult {
  pagination: PaginationState;
  paginationConfig: any;
  setPagination: (state: Partial<PaginationState>) => void;
  resetPagination: () => void;
  handleTableChange: (page: number, pageSize?: number) => void;
}

export const usePagination = (config: PaginationConfig = {}): UsePaginationResult => {
  const {
    initialPage = 1,
    initialPageSize = 10,
    showSizeChanger = true,
    showQuickJumper = true,
    showTotal = (total: number) => `共 ${total} 条记录`
  } = config;

  const [pagination, setPaginationState] = useState<PaginationState>({
    current: initialPage,
    pageSize: initialPageSize,
    total: 0,
  });

  const setPagination = useCallback((state: Partial<PaginationState>) => {
    setPaginationState(prev => ({ ...prev, ...state }));
  }, []);

  const resetPagination = useCallback(() => {
    setPaginationState({
      current: initialPage,
      pageSize: initialPageSize,
      total: 0,
    });
  }, [initialPage, initialPageSize]);

  const handleTableChange = useCallback((page: number, pageSize?: number) => {
    setPagination({
      current: page,
      pageSize: pageSize || pagination.pageSize,
    });
  }, [pagination.pageSize, setPagination]);

  const paginationConfig = {
    current: pagination.current,
    pageSize: pagination.pageSize,
    total: pagination.total,
    showSizeChanger,
    showQuickJumper,
    showTotal,
    onChange: handleTableChange,
  };

  return {
    pagination,
    paginationConfig,
    setPagination,
    resetPagination,
    handleTableChange,
  };
};